<template>
  <div class="min-h-screen bg-base-100">
    <div class="blog-container py-8">

      <!-- Top Action Bar -->
      <div class="flex items-center justify-between mb-8">
        <h1 class="text-3xl font-bold">{{ isEditMode ? '编辑文章' : '创建新文章' }}</h1>
        
        <div class="flex items-center gap-3">
          <button @click="goBack" class="btn btn-ghost">
            取消
          </button>
          <div class="dropdown dropdown-end">
            <label tabindex="0" class="btn btn-primary btn-sm">
              {{ isDraft ? '保存' : '发布' }}
              <icon-heroicons-chevron-down class="w-4 h-4 ml-1" />
            </label>
            <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52">
              <li>
                <button @click="savePost(false)" class="flex items-center w-full">
                  <icon-heroicons-archive-box class="w-4 h-4 mr-2" />
                  保存为草稿
                </button>
              </li>
              <li>
                <button @click="savePost(true)" class="flex items-center w-full">
                  <icon-heroicons-paper-airplane class="w-4 h-4 mr-2" />
                  发布文章
                </button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      
      <!-- Main Content Grid -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

        <!-- Left Column (Main Editor Area) -->
        <div class="lg:col-span-2 space-y-6">
          <!-- 文章标题输入 -->
          <div class="form-control">
            <input 
              v-model="postTitle" 
              type="text" 
              placeholder="文章标题" 
              class="input input-lg input-bordered text-2xl font-bold w-full bg-base-100" />
          </div>

          <!-- 编辑器选择 -->
          <div class="form-control">
            <label class="label"><span class="label-text font-medium">编辑器类型</span></label>
            <div class="flex gap-2">
              <button 
                @click="editorType = 'markdown'" 
                class="btn" 
                :class="{ 'btn-primary': editorType === 'markdown', 'btn-outline': editorType !== 'markdown' }">
                Markdown
              </button>
              <button 
                @click="editorType = 'richtext'" 
                class="btn" 
                :class="{ 'btn-primary': editorType === 'richtext', 'btn-outline': editorType !== 'richtext' }">
                富文本
              </button>
            </div>
          </div>
          
          <!-- 编辑器区域 -->
          <div class="card bg-base-100 shadow border border-base-200">
            <div class="card-body p-0">
              <!-- Markdown 编辑器 -->
              <div v-if="editorType === 'markdown'" class="min-h-[400px]">
                <textarea 
                  v-model="content" 
                  class="w-full min-h-[400px] p-4 font-mono resize-y bg-transparent focus:outline-none" 
                  placeholder="在此输入 Markdown 内容..."></textarea>
              </div>
              
              <!-- 富文本编辑器 -->
              <div v-else class="min-h-[400px]">
                <div id="rich-text-editor" class="min-h-[400px]"></div>
              </div>
            </div>
          </div>
          
          <!-- 预览 -->
          <div v-if="editorType === 'markdown'">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-xl font-bold">预览</h3>
              <div>
                <button @click="previewActive = !previewActive" class="btn btn-sm btn-outline">
                  {{ previewActive ? '隐藏预览' : '显示预览' }}
                </button>
              </div>
            </div>
            
            <div v-if="previewActive" class="card bg-base-100 shadow border border-base-200">
              <div class="card-body prose max-w-none">
                <div v-html="renderedContent"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- Right Column (Metadata & Settings) -->
        <div class="lg:col-span-1 space-y-6">
          <!-- 封面图片输入 -->
          <div class="form-control card bg-base-200 p-4 rounded-lg">
            <label class="label">
              <span class="label-text font-medium">封面图片</span>
            </label>
            <div class="flex gap-3">
              <input 
                v-model="coverImage" 
                type="text" 
                placeholder="图片URL" 
                class="input input-bordered flex-1" />
              <button 
                v-if="coverImage" 
                @click="previewOpen = true" 
                class="btn btn-outline btn-sm">
                预览
              </button>
            </div>
            <div v-if="coverImage" class="mt-3 max-h-40 overflow-hidden rounded">
              <img :src="coverImage" alt="封面预览" class="w-full h-auto object-cover" />
            </div>
          </div>
          
          <!-- 文章摘要输入 -->
          <div class="form-control card bg-base-200 p-4 rounded-lg">
            <label class="label">
              <span class="label-text font-medium">文章摘要</span>
            </label>
            <textarea 
              v-model="excerpt" 
              class="textarea textarea-bordered h-24" 
              placeholder="输入文章摘要（可选）"></textarea>
          </div>
          
          <!-- 标签选择 -->
          <div class="form-control card bg-base-200 p-4 rounded-lg">
            <label class="label justify-between">
              <span class="label-text font-medium">标签</span>
              <button @click="openTagModal = true" class="btn btn-xs btn-ghost">
                管理标签
              </button>
            </label>
            <div class="flex flex-wrap gap-2 mt-2">
              <div 
                v-for="tag in allTags" 
                :key="tag.id" 
                @click="toggleTag(tag.id)"
                class="badge badge-lg cursor-pointer transition-colors duration-200 ease-in-out"
                :class="[selectedTags.includes(tag.id) ? 'badge-primary' : 'badge-outline hover:bg-primary hover:text-primary-content']">
                {{ tag.name }}
              </div>
              <div v-if="allTags.length === 0" class="text-sm opacity-70 mt-1">
                无标签，请先创建标签
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 底部按钮 (Removed as they are redundant with top ones) -->
      <!-- <div class="flex items-center justify-end gap-2 my-8"> ... </div> -->
    </div>
    
    <!-- 标签管理模态框 -->
    <dialog :class="{ 'modal-open': openTagModal }" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">标签管理</h3>
        
        <div class="mb-4">
          <div class="flex gap-2">
            <input 
              v-model="newTagName" 
              type="text" 
              placeholder="输入标签名称" 
              class="input input-bordered w-full"
              @keyup.enter="addNewTag" />
            <button @click="addNewTag" class="btn btn-primary">添加</button>
          </div>
        </div>
        
        <div class="flex flex-wrap gap-2 mb-4 min-h-[50px]">
          <div v-for="tag in allTags" :key="tag.id" class="badge badge-lg gap-1 badge-outline">
            {{ tag.name }}
            <button @click="deleteTag(tag.id)" class="btn btn-ghost btn-xs p-0 min-h-0 h-4 w-4">
              <icon-heroicons-x-mark class="w-3 h-3" />
            </button>
          </div>
          <div v-if="allTags.length === 0" class="text-sm opacity-70">
            暂无标签
          </div>
        </div>
        
        <div class="modal-action">
          <button @click="openTagModal = false" class="btn">关闭</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button @click="openTagModal = false">关闭</button>
      </form>
    </dialog>
    
    <!-- 封面预览模态框 -->
    <dialog :class="{ 'modal-open': previewOpen }" class="modal">
      <div class="modal-box w-11/12 max-w-4xl">
        <button @click="previewOpen = false" class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
        <h3 class="font-bold text-lg mb-4">封面预览</h3>
        <img :src="coverImage" alt="封面预览" class="w-full h-auto object-contain max-h-[80vh]" />
        <div class="modal-action mt-4">
          <button @click="previewOpen = false" class="btn">关闭</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button @click="previewOpen = false">关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBlogStore } from '@/stores/blogStore';
import { useSettingsStore } from '@/stores/settingsStore';
import { marked } from 'marked';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import Quill from 'quill';

const route = useRoute();
const router = useRouter();
const blogStore = useBlogStore();
const settingsStore = useSettingsStore();

// 判断是否为编辑模式
const isEditMode = computed(() => !!route.params.id);
const postId = computed(() => route.params.id as string);

// 文章数据
const postTitle = ref('');
const content = ref('');
const excerpt = ref('');
const coverImage = ref('');
const selectedTags = ref<string[]>([]);
const isDraft = ref(true);

// 编辑器设置
const editorType = ref(settingsStore.editorType);
const previewActive = ref(true);
const quillEditor = ref<Quill | null>(null);

// 标签管理
const allTags = computed(() => blogStore.tags);
const newTagName = ref('');
const openTagModal = ref(false);

// 预览模态框
const previewOpen = ref(false);

// Markdown 渲染
const renderedContent = computed(() => {
  return marked(content.value);
});

// 加载文章数据（编辑模式）
onMounted(() => {
  if (isEditMode.value) {
    const post = blogStore.getPostById(postId.value);
    if (post) {
      postTitle.value = post.title;
      content.value = post.content;
      excerpt.value = post.excerpt;
      coverImage.value = post.coverImage || '';
      selectedTags.value = [...post.tags];
      isDraft.value = !post.isPublished;
    } else {
      router.push('/editor');
    }
  }
  
  // 初始化富文本编辑器
  if (editorType.value === 'richtext') {
    initRichTextEditor();
  }
  
  // 保存用户选择的编辑器类型作为默认值
  settingsStore.setEditorType(editorType.value);
});

// 监听编辑器类型改变
watch(editorType, (newValue) => {
  settingsStore.setEditorType(newValue);
  
  // 当切换到富文本编辑器时初始化
  if (newValue === 'richtext') {
    setTimeout(() => {
      initRichTextEditor();
    }, 100);
  }
});

// 初始化富文本编辑器
const initRichTextEditor = () => {
  const container = document.getElementById('rich-text-editor');
  if (!container) return;
  
  quillEditor.value = new Quill(container, {
    theme: 'snow',
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean'],
        ['link', 'image', 'video']
      ]
    },
    placeholder: '在此输入内容...'
  });
  
  // 设置初始内容
  quillEditor.value.root.innerHTML = content.value;
  
  // 监听内容变化
  quillEditor.value.on('text-change', () => {
    if (quillEditor.value) {
      content.value = quillEditor.value.root.innerHTML;
    }
  });
};

// 切换标签选择
const toggleTag = (tagId: string) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index === -1) {
    selectedTags.value.push(tagId);
  } else {
    selectedTags.value.splice(index, 1);
  }
};

// 添加新标签
const addNewTag = () => {
  if (newTagName.value.trim()) {
    const tagId = blogStore.addTag({ name: newTagName.value.trim() });
    selectedTags.value.push(tagId);
    newTagName.value = '';
  }
};

// 删除标签
const deleteTag = (tagId: string) => {
  if (confirm('确定要删除此标签吗？')) {
    blogStore.deleteTag(tagId);
    const index = selectedTags.value.indexOf(tagId);
    if (index !== -1) {
      selectedTags.value.splice(index, 1);
    }
  }
};

// 保存文章
const savePost = (published = false) => {
  if (!postTitle.value.trim()) {
    alert('请输入文章标题');
    return;
  }
  
  if (!content.value.trim()) {
    alert('请输入文章内容');
    return;
  }
  
  // 确保富文本编辑器内容同步
  if (editorType.value === 'richtext' && quillEditor.value) {
    content.value = quillEditor.value.root.innerHTML;
  }
  
  const postData = {
    title: postTitle.value.trim(),
    content: content.value,
    excerpt: excerpt.value.trim(),
    coverImage: coverImage.value.trim(),
    tags: selectedTags.value,
    isPublished: published,
  };
  
  if (isEditMode.value) {
    blogStore.updatePost(postId.value, postData);
    router.push(`/blog/${postId.value}`);
  } else {
    const newPostId = blogStore.addPost(postData);
    router.push(`/blog/${newPostId}`);
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 组件销毁时清理
onBeforeUnmount(() => {
  quillEditor.value = null;
});
</script>

<style scoped>
/* Add specific styles for the editor view if needed */
.blog-container {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  padding-left: 1rem;
  padding-right: 1rem;
}

/* Improve Quill editor focus outline */
:deep(.ql-container.ql-snow) {
  border-radius: 0 0 var(--rounded-btn, 0.5rem) var(--rounded-btn, 0.5rem); /* Match DaisyUI border radius */
  border-color: var(--fallback-bc, oklch(var(--bc) / 0.2));
}
:deep(.ql-toolbar.ql-snow) {
  border-radius: var(--rounded-btn, 0.5rem) var(--rounded-btn, 0.5rem) 0 0;
  border-color: var(--fallback-bc, oklch(var(--bc) / 0.2));
}
:deep(.ql-container.ql-snow:focus-within) {
   border-color: var(--fallback-bc, oklch(var(--bc) / 0.4));
   box-shadow: 0 0 0 2px var(--fallback-bc, oklch(var(--bc) / 0.2));
}

/* Style for Markdown textarea */
textarea.bg-transparent:focus {
  outline: none;
  box-shadow: none;
}
</style> 